/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-8-31 下午2:09 Created by dwzhang
 */
package com.jade.framework.base.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jade.framework.base.JadeSystem;

/**
 * Json的工具类。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-8-31 下午2:09
 */
public class JsonUtils
{
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String writeToString(Object obj)
    {
        try {
            return objectMapper.writeValueAsString(obj);
        }
        catch (Exception e) {
            JadeSystem.getLog().warn("Can't write object to string:" + e.getMessage());
            return null;
        }
    }

    public static <T> T readFromString(String str, Class<T> clazz)
    {
        try {
            return (T) objectMapper.readValue(str, clazz);
        }
        catch (Exception e) {
            JadeSystem.getLog().warn("Can't read object from string:" + e.getMessage());
            return null;
        }
    }
}
